package com.itheima.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SecurityConfigUserService implements UserDetailsService {
    //模拟数据库的数据
    private static Map<String,SysUser> userDb = new HashMap<>();

    static {
        SysUser user1 = new SysUser();
        user1.setUsername("admin");
        user1.setPassword(new BCryptPasswordEncoder().encode("123"));
        // 用户权限与角色
        Role role1 = new Role("系统管理员","ROLE_ADMIN");
        role1.getPermissions().add(new Permission("添加权限","add"));
        role1.getPermissions().add(new Permission("删除权限","delete"));
        role1.getPermissions().add(new Permission("更新权限","update"));
        role1.getPermissions().add(new Permission("查询权限","find"));
        user1.getRoles().add(role1);

        userDb.put(user1.getUsername(),user1);

        SysUser userZhangSan = new SysUser();
        userZhangSan.setUsername("zhangsan");
        userZhangSan.setPassword(new BCryptPasswordEncoder().encode("123"));
        Role role2 = new Role("普通用户","ROLE_USER");
        role2.getPermissions().add(new Permission("查询权限","find"));
        userZhangSan.getRoles().add(role2);
        userDb.put(userZhangSan.getUsername(),userZhangSan);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userDb.get(username);
        if (sysUser!=null){
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
            for (Role role : sysUser.getRoles()) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getKeyword());
                grantedAuthorityList.add(authority);
                for (Permission permission : role.getPermissions()) {
                    SimpleGrantedAuthority authority1 = new SimpleGrantedAuthority(permission.getKeyword());
                    grantedAuthorityList.add(authority1);
                }
            }
            User user = new User(sysUser.getUsername(), sysUser.getPassword(), grantedAuthorityList);
            return user;
        }
        return null;
    }
}
